package com.krtech.wecard.module.sys.controller;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.krtech.wecard.framework.exception.BusinessException;
import com.krtech.wecard.framework.model.CommRes;
import com.krtech.wecard.framework.utils.LoginUtil;
import com.krtech.wecard.module.pub.entity.CardInfoUser;
import com.krtech.wecard.module.pub.service.CardInfoUserService;
import com.krtech.wecard.module.sys.entity.StatisticalMain;
import com.krtech.wecard.module.sys.entity.StatisticalMainQuery;
import com.krtech.wecard.module.sys.entity.SysUser;
import com.krtech.wecard.module.sys.enums.StatisticalMainEnums;
import com.krtech.wecard.module.sys.mapper.StatisticalMainMapper;
import com.krtech.wecard.module.sys.pojo.TopVo;
import com.krtech.wecard.module.sys.service.StatisticalMainService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 统计查询
 */
@Api(tags = "统计表")
@RestController
@RequestMapping("/sys/statistical")
@Slf4j
public class StatisticalMainController {

    @Autowired
    private StatisticalMainService statisticalMainService;

    @Autowired
    private StatisticalMainMapper statisticalMainMapper;

    @Autowired
    private CardInfoUserService cardInfoUserService;


    /**
     * 埋点
     *      定义激活人数的字段为： ACTIVATION
     *      定义小程序访问：除了激活之外都是小程序访问
     *
     */
    @PutMapping("/addBuriedPoint")
    @ApiOperation(value = "埋点 必填参数，moduleName")
    public Boolean addBuriedPoint(@RequestBody StatisticalMain statisticalMain) {
        return statisticalMainService.addBuriedPoint(statisticalMain);
    }


    @GetMapping("/query")
    @ApiOperation(value = "查询统计情况")
    public CommRes query(StatisticalMainQuery statisticalMainQuery) {
        if (statisticalMainQuery.getModuleName().equals(StatisticalMainEnums.ACTIVATION)){
            QueryWrapper<CardInfoUser> wrapper = new QueryWrapper<>();

            Date startTime = statisticalMainQuery.getStartTime();
            Date endtTime = statisticalMainQuery.getEndtTime();
            String start = DateUtil.format(startTime, "yyyy-MM-dd") + " 00:00:00";
            String end = DateUtil.format(endtTime, "yyyy-MM-dd") + " 23:59:59";

            wrapper.between(CardInfoUser.COL_CREATED_TIME,start,end);

            int count = cardInfoUserService.count(wrapper);
            return CommRes.ok(count);
        }

        QueryWrapper<StatisticalMain> wrapper = new QueryWrapper<>();

        if (statisticalMainQuery.getModuleName().equals(StatisticalMainEnums.APPLETACCESS)){
            //查询小程序访问，除了激活之外所有，都是小程序访问
//            wrapper.ne(StatisticalMain.COL_MODULE_NAME,StatisticalMainEnums.ACTIVATION);
        }else {
            wrapper.eq(StatisticalMain.COL_MODULE_NAME,statisticalMainQuery.getModuleName());
        }
        if (statisticalMainQuery.getStartTime() != null && statisticalMainQuery.getEndtTime() != null){
            wrapper.between(StatisticalMain.COL_ACCESS_TIME,statisticalMainQuery.getStartTime(),statisticalMainQuery.getEndtTime());
        }
        if (statisticalMainQuery.getIdentity() != null){
            //根据身份查询条件
            wrapper.eq(StatisticalMain.COL_IDENTITY,statisticalMainQuery.getIdentity());
        }

        if (statisticalMainQuery.getUserId() != null){
            //根据用户id查询条件
            wrapper.eq(StatisticalMain.COL_USER_ID,statisticalMainQuery.getUserId());
        }

        List<StatisticalMain> statisticalMainList = statisticalMainService.list(wrapper);
        int oneDayCount = statisticalMainList.stream().mapToInt(one -> one.getCount().intValue()).sum();

        return CommRes.ok(oneDayCount);
    }

    @GetMapping("/querySevenDay")
    @ApiOperation(value = "查询七天访问人数")
    public CommRes<List<Map<String,Object>>> querySevenDay(StatisticalMain statisticalMain) {
        //查询七天访问人数

        DateTime time = DateUtil.parse(DateUtil.today(), "yyyy-MM-dd");
        if (statisticalMain.getAccessTime() != null){
            time = DateUtil.parse(DateUtil.format(statisticalMain.getAccessTime(),"yyyy-MM-dd"),"yyyy-MM-dd");
        }
        //得到七天的时间



        List<Map<String,Object>> list = new ArrayList<>();
        //抽出-6 和1到静态值
        for (int offset = -6;offset<1;offset++){
            DateTime sevenDayBefore = DateUtil.offset(time, DateField.DAY_OF_YEAR, offset);
            String sevenDayBeforeStr = DateUtil.format(sevenDayBefore, "yyyy-MM-dd");

            List<StatisticalMain> statisticalMainList = statisticalMainMapper.getListByaccessTime(sevenDayBeforeStr,statisticalMain.getModuleName());
            int oneDayCount = statisticalMainList.stream().mapToInt(one -> one.getCount().intValue()).sum();

            Map<String, Object> map = new HashMap<>();
            map.put("accessTime",sevenDayBeforeStr);
            map.put("count",oneDayCount);
            list.add(map);
        }

        return CommRes.ok(list);
    }

    @GetMapping("/top")
    @ApiOperation(value = "访问最多应用排名及访问频次")
    public CommRes top() {
        List<TopVo> top = statisticalMainMapper.top();

        return CommRes.ok(top);
    }

}
